package org.tis.tools.auth.security.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.NoSuchClientException;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.tis.tools.auth.security.entity.LoginRequest;
import org.tis.tools.model.common.ResultVO;

import javax.validation.constraints.NotBlank;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

/**
 * describe: 自定义端点用于退出
 *
 * @author zhaoch
 * @date 2018/8/28
 **/
@RestController
public class AuthController {

    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);
    @Autowired
    private TokenEndpoint tokenEndpoint;

    @Autowired
    @Qualifier("consumerTokenServices")
    private ConsumerTokenServices consumerTokenServices;

    @PostMapping("/login")
    public ResultVO login(@RequestBody @Validated LoginRequest request) {
        logger.info("login  start ......");
        Map<String, String> parameters = new HashMap<>(3);
        // 设置授权类型为密码模式
        parameters.put("grant_type", "password");
        parameters.put("username", request.getUsername());
        parameters.put("password", request.getPassword());
        Collection<GrantedAuthority> grantedAuthorities = new HashSet<>();
        // 此处不能为空
        grantedAuthorities.add(new SimpleGrantedAuthority("admin"));
        Authentication authentication = new UsernamePasswordAuthenticationToken(
                request.getClientId(), request.getClientSecret(), grantedAuthorities);

        try {
            ResponseEntity<OAuth2AccessToken> responseEntity = tokenEndpoint.postAccessToken(authentication, parameters);
            logger.info("login end ......");
            return ResultVO.success(responseEntity.getBody());
        } catch (NoSuchClientException e) {
            logger.error("login error 应用不存在：", e);
            return ResultVO.error("应用不存在");
        } catch (BadCredentialsException e) {
            logger.error("login error 应用密钥错误：");
            return ResultVO.error("应用密钥错误");
        } catch (InvalidGrantException e) {
            logger.error("login error  用户名密码不正确 ：", e);
            return ResultVO.error("用户名密码不正确");
        } catch (Exception e) {
            logger.error("login error ：", e);
            return ResultVO.error("登录失败" + e.getMessage());
        }
    }

    /**
     * 退出登录
     * @param accessToken
     * @return
     */
    @DeleteMapping("/exit/{accessToken}")
    public ResultVO exit(@NotBlank(message = "token不能为空！") @PathVariable String accessToken) {
        consumerTokenServices.revokeToken(accessToken);
        return ResultVO.success("注销成功！");
    }



}
